package com.gy.assistant.ui.chat.peer;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import im.zego.zim.ZIM;
import im.zego.zim.callback.ZIMConversationMessageReceiptReadSentCallback;
import im.zego.zim.callback.ZIMUsersInfoQueriedCallback;
import im.zego.zim.entity.ZIMCommandMessage;
//import im.zego.zim.entity.ZIMCustomMessage;
import im.zego.zim.entity.ZIMCustomMessage;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMErrorUserInfo;
import im.zego.zim.entity.ZIMMessage;
import im.zego.zim.entity.ZIMMessageReceiptInfo;
import im.zego.zim.entity.ZIMTextMessage;
import im.zego.zim.entity.ZIMUserFullInfo;
import im.zego.zim.enums.ZIMConversationType;
import im.zego.zim.enums.ZIMErrorCode;
import im.zego.zim.enums.ZIMMessageDirection;
import im.zego.zim.enums.ZIMMessageReceiptStatus;
import im.zego.zim.enums.ZIMMessageType;
import com.gy.assistant.MyApplication;
import com.gy.assistant.R;
import com.gy.assistant.SDKManager;
import com.gy.assistant.enums.ChatItemType;
import com.gy.assistant.entity.MessageInfo;
import com.gy.assistant.ui.chat.base.ZIMChatBaseActivity;


public class ZIMPeerChatActivity extends ZIMChatBaseActivity implements SDKManager.OnReceivePeerMessage {

    public static void actionStart(Activity activity, String conversationID, String conversationName,String draft) {
        Intent intent = new Intent(activity, ZIMPeerChatActivity.class);
        intent.putExtra("conversationID", conversationID);
        intent.putExtra("conversationName", conversationName);
        intent.putExtra("draft", draft);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        activity.startActivity(intent);
    }

    private static final String TAG = "ZIMPeerChatActivity";
    private static final int QUERY_PEER_MESSAGE_COUNT = 30;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.zimConversationType = ZIMConversationType.PEER;
        if (conversationName != null && !"".equals(conversationName)) {
            setTitle(conversationName);
        } else {
            setTitle(conversationID);
        }
        getUserInfo();
        SDKManager.sharedInstance().clearConversationUnreadMessageCount(conversationID, ZIMConversationType.PEER);
        SDKManager.sharedInstance().addReceivePeerMessageCallback(this);
        SDKManager.sharedInstance().setConversationMessageReceiptChangedCallback(new SDKManager.OnConversationMessageReceiptChangedCallback() {
            @Override
            public void onConversationMessageReceiptChanged(ZIM zim, ArrayList<ZIMMessageReceiptInfo> infos) {
               List<MessageInfo> messageInfoList =  chatContentAdapter.getMessageInfoList();
               if (messageInfoList!=null){
                   for (ZIMMessageReceiptInfo info : infos) {
                       if (info.conversationID.equals(conversationID) && zimConversationType == info.conversationType){
                           int position = 0;
                           for (int i = 0; i < messageInfoList.size(); i++) {
                               if (messageInfoList.get(i).getZIMMessage().getMessageID() == info.messageID) {
                                   position = i;
                                   break;
                               }
                           }
                           if (position!=0){
                               //找到了会话已读的锚点，再去更改，这里的changed只会更改自己发送的
                               for (int i = 0; i < messageInfoList.size(); i++) {
                                   if (i <= position && messageInfoList.get(i).getZIMMessage().getDirection() == ZIMMessageDirection.SEND){
                                       messageInfoList.get(i).setZimMessageReceiptStatus(ZIMMessageReceiptStatus.DONE);
                                       chatContentAdapter.notifyItemChanged(i);
                                   }
                               }
                           }
                       }
                   }
               }
            }
        });
        SDKManager.sharedInstance().queryPeerMessage(conversationID, null, QUERY_PEER_MESSAGE_COUNT, true, ZIMPeerChatActivity.this);
        sendConversationMessageReceiptRead();
    }

    private void getUserInfo(){
        ArrayList<String > userIds = new ArrayList<>();
        userIds.add(conversationID);
        userIds.add(MyApplication.sUserId);
        SDKManager.sharedInstance().queryUsersInfo(userIds,false, new ZIMUsersInfoQueriedCallback() {
            @Override
            public void onUsersInfoQueried(ArrayList<ZIMUserFullInfo> userList, ArrayList<ZIMErrorUserInfo> errorUserList, ZIMError errorInfo) {
                if (errorInfo.code == ZIMErrorCode.SUCCESS){
                    HashMap<String,String> map = new HashMap<>();
                    for (ZIMUserFullInfo zimUserFullInfo : userList) {
                        map.put(zimUserFullInfo.baseInfo.userID,zimUserFullInfo.userAvatarUrl);
                    }
                    if (!map.isEmpty()){
                        chatContentAdapter.setAvatarMap(map);
                        chatContentAdapter.notifyItemRangeChanged(0,chatContentAdapter.getItemCount());
                    }
                }
            }
        });
    }
    private void sendConversationMessageReceiptRead() {
        SDKManager.sharedInstance().sendConversationMessageReceiptRead(conversationID, zimConversationType, new ZIMConversationMessageReceiptReadSentCallback() {
            @Override
            public void onConversationMessageReceiptReadSent(String conversationID, ZIMConversationType conversationType, ZIMError errorInfo) {
                if (errorInfo.code == ZIMErrorCode.SUCCESS){
                    List<MessageInfo> messageInfoList =  chatContentAdapter.getMessageInfoList();
                    for (int i = 0; i < messageInfoList.size(); i++) {
                        if (messageInfoList.get(i).getZIMMessage().getDirection() == ZIMMessageDirection.RECEIVE && messageInfoList.get(i).getZimMessageReceiptStatus() == ZIMMessageReceiptStatus.PROCESSING){
                            messageInfoList.get(i).setZimMessageReceiptStatus(ZIMMessageReceiptStatus.DONE);
                            chatContentAdapter.notifyItemChanged(i);
                        }
                    }
                }
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void sendMsg(String content) {
        if ("".equals(content.replace(" ", ""))) {
            Toast.makeText(ZIMPeerChatActivity.this, "Please enter valid content", Toast.LENGTH_LONG).show();
            return;
        }

        String userName = SDKManager.sharedInstance().zimUserInfo.userName;
        if (userName != null) {
            userName = SDKManager.sharedInstance().zimUserInfo.userID;
        }

        CheckBox cbCommand = findViewById(R.id.isCommand);
        CheckBox cbCustom = findViewById(R.id.isCustom);
        ZIMMessage zimMessage;
        String pushContent = "";
        if (cbCommand.isChecked()) {
            ZIMCommandMessage commandMessage = new ZIMCommandMessage();
            commandMessage.message = content.getBytes(StandardCharsets.UTF_8);
            zimMessage = commandMessage;
        }else if (cbCustom.isChecked()){
            ZIMCustomMessage customMessage = new ZIMCustomMessage(content, 100);
            customMessage.searchedContent="searchContent";
            zimMessage = customMessage;
        }else {
            ZIMTextMessage zimTextMessage = new ZIMTextMessage();
            zimTextMessage.message = content;
            zimMessage = zimTextMessage;
            pushContent = content;
        }
        setMessageMention(zimMessage);
        SDKManager.sharedInstance().sendPeerMessage(zimMessage, conversationID, getSendConfig(userName,pushContent), this);
    }

    @Override
    protected void onLoadMsg() {
        super.onLoadMsg();
        MessageInfo info = chatContentAdapter.getMessage(0);
        if (info != null) {
            SDKManager.sharedInstance().queryPeerMessage(conversationID, info.getZIMMessage(), QUERY_PEER_MESSAGE_COUNT, true, ZIMPeerChatActivity.this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SDKManager.sharedInstance().removeReceivePeerMessageCallback(this);
    }

    @Override
    public void onReceivePeerMessage(ZIM zim, ArrayList<ZIMMessage> messageList, String fromUserID) {
        for (ZIMMessage message : messageList) {
            if (message.getConversationID().equals(conversationID)) {
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT);
                messageInfo.setZIMMessage(message);
                addMsg(messageInfo);
            }
        }
        SDKManager.sharedInstance().clearConversationUnreadMessageCount(conversationID, ZIMConversationType.PEER);
    }

    @Override
    public void onMessageQueried(String conversationID, ZIMConversationType conversationType, ArrayList<ZIMMessage> arrayList, ZIMError zimError) {
        super.onMessageQueried(conversationID, conversationType, arrayList, zimError);
        Collections.reverse(arrayList);
        for (ZIMMessage message : arrayList) {
            MessageInfo messageInfo = new MessageInfo();
            if (message.getType() == ZIMMessageType.SYSTEM||message.getType() == ZIMMessageType.REVOKE){
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_CENTER);
            }else if (message.getSenderUserID().equals(SDKManager.sharedInstance().zimUserInfo.userID)) {
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_RIGHT);
            } else {
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT);
            }
            messageInfo.setZIMMessage(message);
            addMsgToTop(messageInfo);
        }

    }
}
